package com.example.springaiquickstart.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/ai")
public class ChatController {

    /**
     * 与deepseek的模型进行交互
     */
    @Autowired
    private DeepSeekChatModel deepSeekChatModel;


    @GetMapping("/generate")
    public String generate(@RequestParam(name = "message", defaultValue = "你是谁？") String message) {
        System.out.println("message:" + message);
        String resp = deepSeekChatModel.call(message);
        System.out.println("resp:" + resp);
        return resp;
    }

    /**
     * 流式返回：Json格式
     * @param message
     * @return
     */
    @GetMapping("/generateStream")
    public Flux<String> generateStream(@RequestParam(name = "message", defaultValue = "你是谁？") String message, HttpServletResponse  response) {
        response.setCharacterEncoding("utf-8");
        Prompt prompt = new Prompt(message);
        Flux<ChatResponse> stream = deepSeekChatModel.stream(prompt);
        Flux<String> map = stream.mapNotNull(chatResponse -> chatResponse.getResult().getOutput().getText());
        return map;
    }

}
